// 获取 pages.json
import pagesJson from '@/pages.json';
import useUserStore from '@/store/modules/user.js'

// 主包路径
const routes = [...pagesJson.pages];
// 分包路径
const subPackages = pagesJson.subPackages || [];

// 解析分包路径
subPackages.forEach(({
	root,
	pages
}) => {
	pages.forEach(page => {
		// 拼接分包路径
		page.path = `${root}/${page.path}`;
		routes.push(page);
	});
});

// 封装通用跳转函数
const navigate = (path, type = 'navigateTo') => {
	// 基本参数检查
	if (typeof path !== 'string' || !path) {
		return false;
	}
	// 获取路由路径（去掉参数）
	const routePath = path.includes('?') ? path.split('?')[0] : path;
	// 获取用户信息
	const userStore = useUserStore();
	const userInfo = userStore.userInfo;
	// 查找匹配的路由配置
	const route = routes.find(item => `/${item.path}` === routePath || item.path === routePath);
	// 检查是否需要登录
	if (route?.needLogin && !userInfo) {
		uni.navigateTo({
			url: '/pages/login/index'
		});
		return false;
	}

	const navigationMethods = {
		navigateTo: uni.navigateTo,
		redirectTo: uni.redirectTo,
		reLaunch: uni.reLaunch,
		switchTab: uni.switchTab
	};
	const navigateMethod = navigationMethods[type] || uni.navigateTo;
	// 执行跳转
	navigateMethod({
		url: path
	});
	return true;
};

/**
 * @desc 普通跳转
 * @param path  跳转路径
 */
const navigateTo = (path = '') => navigate(path);

/**
 * @desc 跳转 tab 页面
 * @param path  跳转路径
 */
const switchTab = (path) => navigate(path, 'switchTab');

/**
 * @desc 关闭当前页，跳转
 * @param path  跳转路径
 */
const redirectTo = (path) => navigate(path, 'redirectTo');

/**
 * @desc 关闭所有页，跳转
 * @param path  跳转路径
 */
const reLaunch = (path) => navigate(path, 'reLaunch');

/**
 * @desc 返回上一页
 */
const toBack = () => uni.navigateBack({
	delta: 1
});

export {
	navigateTo,
	switchTab,
	redirectTo,
	reLaunch,
	toBack,
};